package com.joymart.dictionary;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.joymart.common.system.IdGenerator;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

@Service
public class DictionaryService {

    @Autowired
    private DictionaryItemRepository dictionaryItemRepository;
    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private IdGenerator idGenerator;

    @Cacheable(value = "dictionaries")
    public Dictionary findByName(String name){
        List<DictionaryItem> items = dictionaryItemRepository.findAllByNameOrderByOrderNo(name);
        Dictionary dictionary = new Dictionary();
        dictionary.setName(name);
        dictionary.setKeyValues(new LinkedHashMap<>());
        items.stream().forEach(item->{
            Dictionary.Value value = new Dictionary.Value();
            value.setText(item.getText());
            Optional.ofNullable(item.getAddition()).map(JSONObject::toMap).ifPresent(value::setAddition);
            dictionary.getKeyValues().put(item.getKey(), value);
        });
        return dictionary;
    }


    @Transactional
    @CacheEvict(value = "dictionaries", key = "#dict.name")
    public void maintainDictionary(Dictionary dict) {
        List<DictionaryItem> items = dictionaryItemRepository.findAllByNameOrderByOrderNo(dict.getName());
        jdbcAggregateTemplate.deleteAll(items);
        List<String> keyset=new ArrayList<>( dict.getKeyValues().keySet());
        for (int i = 0; i < keyset.size(); i++) {
            String key = keyset.get(i);
            Dictionary.Value value = dict.getKeyValues().get(key);
            DictionaryItem dictionaryItem = new DictionaryItem();
            dictionaryItem.setKey(key);
            dictionaryItem.setText(value.getText());
            dictionaryItem.setName(dict.getName());
            dictionaryItem.setId(idGenerator.next());
            dictionaryItem.setAddition(new JSONObject(value.getAddition()));
            dictionaryItem.setOrderNo(i+1);
            jdbcAggregateTemplate.insert(dictionaryItem);
        }
    }
}
